/**
 * 
 */
package org.chengsen.config;

import javax.inject.Inject;

import org.chengsen.dataobject.UserDO;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;

/**
 * @author Jason.zhang
 * 
 */
@Configuration
@Import(PropertyConfig.class)
public class DataSourceConfig {
	@Value("${jdbc.driverClassName}")
	private String driverClassName;
	@Value("${jdbc.url}")
	private String url;
	@Value("${jdbc.username}")
	private String username;
	@Value("${jdbc.password}")
	private String password;

	@Inject
	private PropertyConfig hibernateConfig;

	@Bean(name = "sessionFactory")
	public AnnotationSessionFactoryBean sessionFactory() {
		AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		sessionFactory.setPackagesToScan(new String[] { "org/chengsen/" });
		sessionFactory.setHibernateProperties(hibernateConfig
				.hibernateProperties());
		return sessionFactory;
	}

	// @Bean(name = "sessionFactory")
	public SessionFactory _sessionFactory() {
		return new LocalSessionFactoryBuilder(dataSource())
				.addAnnotatedClasses(UserDO.class).buildSessionFactory();
	}

	private DriverManagerDataSource dataSource() {
		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
	}

	@Bean(name = "driverClassName")
	public String getDriverClassName() {
		return this.driverClassName;
	}
}